<template>
  <rj-table
    :columns="columns"
    :data-source="tableData"
    size="middle"
    bordered
    :row-key="
      (record) =>
        itemName === 'INTF_PACKET' ? record.interfaceShort : record.id
    "
    :loading="loading"
    :pagination="pagination"
    @change="handleTableChange"
    @refeshTable="refeshTableCallBack"
  >
    <template slot="customBlock">
      <div class="table-action">
        <rj-space>
          <span>{{ $t('deviceDetail.updatedTime') }}{{ tableUpdateTime }}</span>
          <!-- <a @click="handelRefreshTable"
            ><a-icon type="sync" /> {{ $t('common.refresh') }}</a
          > -->
        </rj-space>
        <slot></slot>
      </div>
    </template>
    <span slot="macStatus">
      {{ $t('deviceDetail.dynamic') }}
    </span>
    <span slot="updateTime" slot-scope="updateTime">
      {{ formatterDate(updateTime) }}
    </span>
    <span slot="ip" slot-scope="ip">
      {{ ip || '-' }}
    </span>
    <span slot="intf" slot-scope="intf">
      {{ intf || '-' }}
    </span>
    <span slot="protocol" slot-scope="protocol">
      {{ protocol || 'Internet' }}
    </span>
    <span slot="age" slot-scope="age">
      {{ age ? `${(age, $t('wirelessExperience.score1'))}` : '-' }}
    </span>
    <span slot="flags" slot-scope="flags">
      {{ routerFlags[flags] || flags || '-' }}
    </span>
    <span slot="nextIntf" slot-scope="nextIntf">
      {{ nextIntf || '--' }}
    </span>
    <span slot="type" slot-scope="type">
      {{ dhcpType[type] || type || '-' }}
    </span>
    <!-- 收发包数据 -->
    <span slot="flow" slot-scope="text, row"
      >{{ row.input != undefined ? Math.round(row.input / 1024) : '--' }}/{{
        row.output != undefined ? Math.round(row.output / 1024) : '--'
      }}
    </span>
    <span slot="speed" slot-scope="text, row"
      >{{ row.downRate || '--' }}/{{ row.upRate || '--' }}
    </span>
    <span slot="message" slot-scope="text, row"
      >{{ row.inputPacket != undefined ? row.inputPacket : '--' }}/{{
        row.outputPacket != undefined ? row.outputPacket : '--'
      }}
    </span>
    <span slot="Epackt" slot-scope="text, row"
      >{{ row.crcErr || '--' }}/{{ row.fcsErr || '--' }}
    </span>
    <span slot="Bpackt" slot-scope="text, row"
      >{{ row.frame || '--' }}/{{ row.giant || '--' }}
    </span>
    <span slot="ipv6NeighborsType" slot-scope="text"
      >{{
        text == 'STATIC'
          ? $t('deviceDetail.static')
          : $t('deviceDetail.dynamic')
      }}
    </span>
    <span slot="ipv6NeighborsState" slot-scope="text"
      >{{ getIpv6NeighborsState(text) }}
    </span>
  </rj-table>
</template>
<script>
import moment from 'moment-timezone';
import { RjTable } from '@components';
import { requestHttp, maccApi } from '@utils/index';
import * as columns from './columns.js';
import { i18nRender } from '@/locales';
const tableApi = [
  {
    name: i18nRender('deviceDetail.mac'),
    index: 'MAC',
    api: 'GET_TROUBLE_MAC_TABLE',
  },
  {
    name: i18nRender('deviceDetail.arp'),
    index: 'ARP',
    api: 'GET_TROUBLE_ARP_TABLE',
  },
  {
    name: i18nRender('devicede.dhcpList'),
    index: 'DHCP_USER',
    api: 'GET_TROUBLE_DHCP_TABLE',
  },
  {
    name: i18nRender('deviceDetail.routeTable'),
    index: 'ROUTE',
    api: 'GET_TROUBLE_ROUTER_TABLE',
  },
  {
    name: i18nRender('deviceDetail.ip6detail'),
    index: 'IPV6_ROUTE',
    api: 'GET_IPV6_ROUTER_TABLE',
  },
  {
    name: i18nRender('deviceDetail.dhcpSnopinglis'),
    index: 'DHCP_SNOOPING',
    api: 'GET_TROUBLE_DHCP_SNOOPING_TABLE',
  },
  {
    name: i18nRender('deviceDetail.interfacePacketStatistics'),
    index: 'INTF_PACKET',
    api: 'GET_INTERFACE_FLOW_LIST',
  },
  {
    name: i18nRender('deviceDetail.devicelist'),
    index: 'IPV6_NEIGHBORS',
    api: 'DEVICE_IPV6_NEIGHBORS_GET_API',
  },
];
export default {
  name: 'TableItems',
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
    itemName: {
      type: String,
      default: '',
    },
    searchBy: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      loading: false,
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      timer: null, //计数器
      maxTimer: 3, //最大状态询问次数
      tableData: [],
      localData: [],
      tableUpdateTime: '',
      //路由类型
      routerFlags: {
        C: i18nRender('deviceDetail.directiConnection'),
        S: i18nRender('deviceDetail.slient'),
        'S*': i18nRender('deviceDetail.defaultRoute'),
        U: i18nRender('deviceDetail.directiConnection'),
        UG: i18nRender('wanSmart.wanwan'),
        O: i18nRender('deviceDetail.ospfdd'),
        R: i18nRender('deviceDetail.Rip'),
      },
      //dhcp用户类型
      dhcpType: {
        Manual: i18nRender('deviceDetail.slientbind'),
        Automatic: i18nRender('deviceDetail.autodistribute'),
        Solidify: i18nRender('deviceDetail.solidBind'),
      },
    };
  },
  computed: {
    columns() {
      return columns[this.itemName];
    },
    currentTable() {
      return tableApi.find((item) => {
        return item.index === this.itemName;
      });
    },
    timezone() {
      const currentGroup = this.$store.state.Group.groupMap[
        this.deviceInfo.groupId
      ];
      return (currentGroup && currentGroup.timezone) || '';
    },
  },
  components: {
    'rj-table': RjTable,
  },
  mounted() {
    this.loadTableData();
  },
  watch: {
    deviceInfo: {
      handler() {
        this.pagination = {
          page: 1,
          pageSize: 10,
          total: 0,
        };
        this.loadTableData();
      },
      deep: true,
    },
    searchBy: {
      handler() {
        this.pagination = {
          page: 1,
          pageSize: 10,
          total: 0,
        };
        this.loadTableData();
      },
      deep: true,
    },
  },
  methods: {
    handleTableChange(pagination) {
      const pager = { ...this.pagination };
      pager.page = pagination.current;
      pager.pageSize = pagination.pageSize;
      this.pagination = pager;
      if (this.itemName === 'INTF_PACKET') {
        this.tableData = this.getCurrerentDate();
      } else {
        this.loadTableData();
      }
    },
    loadTableData() {
      if (this.currentTable) {
        switch (this.currentTable.index) {
          case 'INTF_PACKET': {
            this.loadPacketData();
            break;
          }
          default: {
            this.loadInfoTable();
            break;
          }
        }
      }
    },
    //加载表项表
    async loadInfoTable() {
      let api = maccApi[this.currentTable.api]
        .replace('{sn}', this.deviceInfo.serialNumber)
        .replace('{page}', this.pagination.page)
        .replace('{per_page}', this.pagination.pageSize);
      const searchList = Object.keys(this.searchBy);
      if (searchList.length > 0) {
        searchList.forEach((item) => {
          api += `&${item}=${this.searchBy[item]}`;
        });
      }
      this.loading = true;
      const res = await requestHttp({
        api,
        method: 'GET',
      });
      this.loading = false;
      if (res && res.code == 0) {
        this.tableUpdateTime = res.updateTime
          ? moment
              .tz(res.updateTime, this.timezone)
              .format('YYYY-MM-DD HH:mm:ss')
          : '';
        this.tableData = res.data || [];
        this.pagination.total = res.count;
      } else {
        this.$message.error(res.msg);
      }
    },
    //加载收发报文表
    async loadPacketData() {
      const api = maccApi[this.currentTable.api];
      this.loading = true;
      const res = await requestHttp({
        api,
        method: 'POST',
        params: {
          sn: this.deviceInfo.serialNumber,
          buildingId: this.deviceInfo.groupId,
          order: 'asc',
        },
      });
      this.loading = false;
      if (res && res.code == 0) {
        this.tableUpdateTime = res.updateTime
          ? moment
              .tz(res.updateTime, this.timezone)
              .format('YYYY-MM-DD HH:mm:ss')
          : '';
        this.localData = res.interfaceFlow || [];
        this.tableData = this.getCurrerentDate();
        this.pagination.total = res.interfaceFlow.length;
      } else {
        this.$message.error(res.msg);
      }
    },
    // handelRefreshTable() {
    //   this.triggerTableDataGet(this.itemName);
    //   //this.loadTableData();
    // },
    formatterDate(updateTime) {
      return updateTime
        ? moment(updateTime).tz(this.timezone).format('YYYY-MM-DD HH:mm:ss')
        : '';
    },
    getCurrerentDate() {
      return this.localData.slice(
        (this.pagination.page - 1) * this.pagination.pageSize,
        this.pagination.page * this.pagination.pageSize
      );
    },
    async triggerTableDataGet(type) {
      const api = maccApi.DEVICE_ENTRYTRIGGER_POST_API.replace(
        '{sn}',
        this.deviceInfo.serialNumber
      ).replace('{type}', type);
      const res = await requestHttp({
        api,
        method: 'POST',
        params: {},
      });
      if (res && res.code == 0) {
        let timerCount = 0;
        this.timer = setInterval(async () => {
          const status = await this.checkDeviceEntryStatus(type);
          if (status && status.code == 0) {
            const state = (status.data && status.data.state) || '';
            switch (state) {
              case 'EXECUTING': {
                break;
              }
              case 'FINISH': {
                clearInterval(this.timer);
                this.loadTableData();
                break;
              }
              default: {
                //this.$message.error(status.msg);
                clearInterval(this.timer);
                break;
              }
            }
          }
          //最大请求次数，状态，避免长时间不状态更新
          timerCount++;
          if (timerCount >= this.maxTimer) {
            clearInterval(this.timer);
            this.loadTableData();
          }
        }, 2000);
      } else {
        this.$message.error(res.msg);
      }
    },
    checkDeviceEntryStatus(type) {
      const api = maccApi.DEVICE_ENTRYTRIGGERSTATUS_GET_API.replace(
        '{sn}',
        this.deviceInfo.serialNumber
      ).replace('{type}', type);
      return requestHttp({
        api,
        method: 'GET',
        params: {},
      });
    },
    //刷新表格
    refeshTableCallBack() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.triggerTableDataGet(this.itemName);
    },
    getIpv6NeighborsState(status) {
      let desc = '';
      switch (status) {
        case 'INCOMPLETE': {
          desc = i18nRender('configLog.nocompleted');
          break;
        }
        case 'REACHABLE': {
          desc = i18nRender('deviceDetail.accessible');
          break;
        }
        case 'STALE': {
          desc = i18nRender('deviceDetail.invaild');
          break;
        }
        case 'DELAY': {
          desc = i18nRender('deviceDetail.delayE');
          break;
        }
        case 'PROBE': {
          desc = i18nRender('deviceDetail.expolre');
          break;
        }
        case 'PERMANENT': {
          desc = i18nRender('wanSmart.static');
          break;
        }
        default: {
          desc = i18nRender('deviceDetail.unknow');
          break;
        }
      }
      return desc;
    },
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
};
</script>
<style lang="less" scoped>
.table-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
</style>
